// ===================================
// <copyright>
// This file is part of LABSMFController.
//
//    LABSMFController is free software: you can redistribute it and/or modify
//    it under the terms of the GNU General Public License as published by
//    the Free Software Foundation, either version 3 of the License, or
//    (at your option) any later version.
//
//    LABSMFController is distributed in the hope that it will be useful,
//    but WITHOUT ANY WARRANTY; without even the implied warranty of
//    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
//    GNU General Public License for more details.
//
//    You should have received a copy of the GNU General Public License
//    along with LABSMFController.  If not, see <http://www.gnu.org/licenses/>.
//    Copyright 2011 David Bakker
//
//</copyright>
// <author>David Bakker</author>
// <email>mailto:DavidFBakker@gmail.com</email>
// <created>Saturday, May 07, 2011</created>
// <lastedit>Saturday, May 07, 2011</lastedit>
// ===================================

using System;
using System.Threading;
using LABSMFController.LABS.Classses;
using LABSMFController.LABS.Devices;

namespace LABSMFController.LABS.Services
{
    public class BubblerServiceClass : BeerService
    {
        public static int MAXBubblers { get { return 3;  } }

        public BubblerDevice[] Bubblers;

        private Thread[] _myBbThreads;
        private BubblerThreadRunner[] _bubblerThreads;


        private  void SetupBubblers()
        {
            Location.Setup();
            Bubblers = new BubblerDevice[MAXBubblers];

            for (int c = 0; c < MAXBubblers; c++)
            {
                switch (c)
                {
                    case Location.HLT:
                        Bubblers[Location.HLT] = new BubblerDevice(Location.Names[c] + " Bubbler",
                                                                   Devs.AnalogInDevice.HLT_Bubbler.PIN,
                                                                   Location.HLT,
                                                                   Convert.ToInt32(
                                                                       Settings.GetSetting("HLTLevelEmpty")));
                        break;
                    case Location.MLT:
                        Bubblers[Location.MLT] = new BubblerDevice(Location.Names[c] + " Bubbler",
                                                                   Devs.AnalogInDevice.MLT_Bubbler.PIN,
                                                                   Location.MLT,
                                                                   Convert.ToInt32(
                                                                       Settings.GetSetting("MLTLevelEmpty")));
                        break;
                    case Location.BK:
                        Bubblers[Location.BK] = new BubblerDevice(Location.Names[c] + " Bubbler", Devs.AnalogInDevice.BK_Bubbler.PIN,
                                                                  Location.BK,
                                                                  Convert.ToInt32(Settings.GetSetting("BKLevelEmpty")));
                        break;
                }
            }
        }
        

        public string GetBubblersClientOutPut()
        {
            string ret = "HEADER:Bubblers:" + Bubblers[0].Header + ";";
            for (int c = 0; c < MAXBubblers; c++)
            {
                ret = ret + "\r\n" + Bubblers[c].GetClientOutPut();
            }
            return ret;
        }

        public override void Configure()
        {
            if ( IsActive)
            {
                BeerProgram.Log(Description + " Already configured");
                return;
            }
            Description = "Bubbler Service";
            BeerProgram.Log(Description + " Configuring");
            SetupBubblers();
            IsActive = false;
            EnableDebug = true;
            _bubblerThreads = new BubblerThreadRunner[MAXBubblers];
            _myBbThreads = new Thread[MAXBubblers];
            BeerProgram.Log(Description + " Done configuring");
        }

        public override void Start()
        {
            StartThreads();
        }


        public override void StartThreads()
        {
            for (int c = 0; c < MAXBubblers; c++)
            {
                _bubblerThreads[c] = new BubblerThreadRunner(Bubblers[c]) { Run = true };
                _myBbThreads[c] = new Thread(_bubblerThreads[c].BubblerThread);
                _bubblerThreads[c].EmptyEvent += BubblerServiceClassEmptyEvent;                 
                _myBbThreads[c].Start();
            }
        }

        void BubblerServiceClassEmptyEvent(object sender, TriggerMessage message)
        {
            InvokeEmptyEvent(message);
        }

        public override void Stop()
        {
            BeerProgram.Log(Description + " Stopping");
            for (int c = 0; c < MAXBubblers; c++)
            {
                if (_bubblerThreads[c] != null)
                    _bubblerThreads[c].Run = false;

                if (_myBbThreads[c] != null)
                    _myBbThreads[c].Abort();
            }
            IsActive = false;
        }

        public void SetLevelTrigger(int location, double qts)
        {
            _bubblerThreads[location].Trigger = qts;
            _bubblerThreads[location].TriggerEvent += BubblerServiceTriggerEvent;
        }

        void BubblerServiceTriggerEvent(object sender, TriggerMessage message)
        {
            InvokeTriggerEvent(message);
        }

        public event TriggerHandler EmptyEvent;
        public void InvokeEmptyEvent(TriggerMessage message)
        {
            TriggerHandler handler = EmptyEvent;
            if (handler != null) handler(this, message);
        }
                
      }

    internal class BubblerThreadRunner
    {
        public delegate void TriggerHandler(object sender, TriggerMessage message);
        public event TriggerHandler TriggerEvent;
        public void InvokeTriggerEvent(TriggerMessage message)
        {
            TriggerHandler handler = TriggerEvent;
            if (handler != null) handler(this, message);
        }

        public event TriggerHandler EmptyEvent;
        public void InvokeEmptyEvent(TriggerMessage message)
        {
            TriggerHandler handler = EmptyEvent;
            if (handler != null) handler(this, message);
        }

        private readonly BubblerDevice _bubbler;
        private double _readingAvgTotal;
        private int _readingCount;
        private double _readingTotal;

        public BubblerThreadRunner(BubblerDevice bubblerDevice)
        {            
            _bubbler = bubblerDevice;
            _readingTotal = 0;
            _readingCount = 0;
            _readingAvgTotal = 0;
            Run = true;
        }

        public bool Run { get; set; }
        public bool TriggerIsActive { get; set; }

        private double _trigger;
        public double Trigger
        {
            get { return _trigger; }
            set
            {
                TriggerIsActive = true;
                _trigger = value;
            }
        }

        private int GetLevel()
        {
            try
            {
                int level = _bubbler.DeviceIn.Read();
                return level;
            }
            catch (Exception ex)
            {
                throw new ApplicationException(ex.Message);
            }
        }

        public void BubblerThread()
        {
            try
            {
                int avgCount = Convert.ToInt32(Settings.GetSetting("AverageCount"));
                int refresh = Convert.ToInt32(Settings.GetSetting("RefeshInterval"));
                long t = DateTime.Now.Ticks;

                while (Run)
                {

                    double v = GetLevel();

                    _readingTotal += v;
                    _readingCount += 1;

                    if (_readingCount > avgCount)
                    {
                        _bubbler.Level = (int) (_readingTotal/avgCount);

                        if (_bubbler.Level == 0)
                        {
                            InvokeEmptyEvent(new TriggerMessage(Location.Names[_bubbler.LocationID], _bubbler.Level));
                        }

                        if (TriggerIsActive)
                        {
                            if (Trigger > 0)
                            {
                                if (_bubbler.Level > Trigger)
                                {
                                    TriggerIsActive = false;
                                    InvokeTriggerEvent(new TriggerMessage(Location.Names[_bubbler.LocationID],
                                                                          _bubbler.Level));
                                }
                            }

                            if (Trigger <= 0)
                            {
                                if (_bubbler.Level < (Trigger*-1) || _bubbler.Level == 0)
                                {
                                    TriggerIsActive = false;
                                    InvokeTriggerEvent(new TriggerMessage(Location.Names[_bubbler.LocationID],
                                                                          _bubbler.Level));
                                }
                            }
                        }

                        _readingCount = 0;
                        _readingTotal = v;
                        avgCount = Convert.ToInt32(Settings.GetSetting("AverageCount"));
                        refresh = Convert.ToInt32(Settings.GetSetting("RefeshInterval"));
                        long t2 = DateTime.Now.Ticks;
                        long b = t2 - t;
                        t = DateTime.Now.Ticks;
                    }
                    Thread.Sleep(refresh);
                }
            }catch(Exception ex)
            {
                BeerProgram.Log(ex.Message,LoggingSeverity.Important);
            }
        }
    }
}